function [newpath,ch] = cr_dir( rpath , varargin ); 
% ======================================================================
% CH_DIR
%
% Create the corresponding output string and at the end 
% Check if the directory exists 
%        If doesn't, create it 
%        If does     do nothing 
%
% Input
% ------
% RPATH     Root path from where to start looking 
%           If [] will be where the invoking code is running from 
% 
% VARARGIN  Variable number of strings to be combined to form a final
%           directory name 
% 
% In the case of UNIX the code will check for the exact case 
% 
% NEWPATH   Corresponding string 
% CH        ==1 if either path exists or was succesfully created 
%           ==0 if could not be created, warning shows up 
%
% 
% Use CH_EXDIR to check & create composite existing directory names 
% 
% Alejandro Justiniano 10/22/2005 
% =========================================================================
cucd = cd; 
nn = nargin; 
ind = isunix; 
if ind== 1  
    sep = '/'; 
else 
    sep = '\'; 
end 

if nn == 1
    error('Need at least 1 input other than the rootpath')
end

if isempty( rpath )
    rpath = pwd ; 
end 
   
newpath =rpath;
if nn > 2
    for ii=1:nn-2
        cd(newpath);
        ch = exist( varargin{ii}, 'dir' );
        if ch == 0
            ch=mkdir(newpath,char(varargin{ii}));
        end
        newpath=[newpath,sep,char(varargin{ii})];
    end
end
cd( newpath )
ch = exist( varargin{nn-1}, 'dir' );

if ch == 0 
    ch = mkdir( newpath , varargin{end} ); 
    if ch == 0 
        disp( ['Warning! Directory ',varargin{end} , 'could not be created'] )
    end 
end
newpath = [newpath,sep,varargin{end}];
cd(cucd);       